package com.homedo.async.mysql.support.convertor.forcolumnval;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author jgshun
 * @date 2020/1/20 1:32 PM
 */
public class DateConditionColumnValConvertor implements ConditionColumnValConvertorI {

    private static final DateTimeFormatter YMD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter YMDHMS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter HMS = DateTimeFormatter.ofPattern("HH:mm:ss");

    private static final DateConditionColumnValConvertor INSTANCE = new DateConditionColumnValConvertor();

    private DateConditionColumnValConvertor() {
    }

    public static DateConditionColumnValConvertor getInstance() {
        return INSTANCE;
    }

    @Override
    public String convertor(Object columnVal) {
        if (columnVal == null) {
            return null;
        }
        StringBuilder valBud = new StringBuilder();
//        valBud.append("'");

        if (columnVal instanceof LocalDate) {
            LocalDate localDate = (LocalDate) columnVal;
            valBud.append(localDate.format(YMD));
        } else if (columnVal instanceof LocalDateTime) {
            LocalDateTime localDateTime = (LocalDateTime) columnVal;
            valBud.append(localDateTime.format(YMDHMS));
        } else if (columnVal instanceof Duration) {
            Duration duration = (Duration) columnVal;
            valBud.append(LocalTime.ofNanoOfDay(duration.toNanos()).format(HMS));
        } else if (columnVal instanceof LocalTime) {
            LocalTime localTime = (LocalTime) columnVal;
            valBud.append(localTime.format(HMS));
        } else if (columnVal instanceof Date) {
            Date date = (Date) columnVal;
            
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            valBud.append(localDateTime.format(YMDHMS));
        } else {
            valBud.append(columnVal);
        }

//        valBud.append("'");

        return valBud.toString();
    }

}
